package org.esisar.dao;

import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.esisar.model.Model;
import org.esisar.model.Book;

public class BookStatementCreator implements StatementCreator{


	private PreparedStatement preparedStatement;
	
	@Override
	public PreparedStatement addStatement(Connection connection, Model model) throws SQLException {
		
		Book book = modelToBook(model);
			
		preparedStatement = connection.prepareStatement("INSERT INTO book (idAlbum,preface,postface,idPicture) VALUES(?,?,?,?)");

		fillModel(book);
	
		return preparedStatement;
		
	}

	@Override
	public PreparedStatement deleteStatement(Connection connection, List<Long> keys) throws SQLException {

		preparedStatement = connection.prepareStatement("DELETE FROM book WHERE idAlbum=?");

		preparedStatement.setLong(1, keys.get(0));
				
		return preparedStatement;
	}

	@Override
	public PreparedStatement updateStatement(Connection connection, Model model)
			throws SQLException {
		
		Book book = modelToBook(model);
		
		preparedStatement = connection.prepareStatement("UPDATE book SET preface = ?, postface = ?, idPicture = ? WHERE idAlbum = ?");

		fillModel(book);
		preparedStatement.setLong(4, book.getIdAlbum());
		
		return preparedStatement;
	}

	private void fillModel(Book book) throws SQLException {
		preparedStatement.setString(1, book.getPreface());
		preparedStatement.setString(2, book.getPostface());
		preparedStatement.setLong(3, book.getIdPicture());
	}

	private Book modelToBook(Model model) {
		Book book;
		
		if (model instanceof Book){
			book = (Book) model;
		}else{
			throw new ClassCastException("Bad object instance");
		}
		return book;
	}
	
	@Override
	public PreparedStatement readStatement(Connection connection, String field,
			String value) throws SQLException {
		throw new UnsupportedOperationException();
	}

	@Override
	public Model fillModel(ResultSet rs) {
		// TODO Auto-generated method stub
		return null;
	}

}
